package com.yueyang.sojourn.server.controller.wx;

import com.github.pagehelper.PageInfo;
import com.yueyang.sojourn.server.common.LoginNeedless;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.controller.BaseController;
import com.yueyang.sojourn.server.model.enums.MerchSaleTypeEnum;
import com.yueyang.sojourn.server.model.enums.ShareDataTypeEnum;
import com.yueyang.sojourn.server.model.enums.ShelfStatusEnum;
import com.yueyang.sojourn.server.model.vo.SojournMerchPriceCalculateVo;
import com.yueyang.sojourn.server.model.vo.SojournMerchPriceCalendarVo;
import com.yueyang.sojourn.server.model.vo.SojournMerchPriceMonthVo;
import com.yueyang.sojourn.server.model.vo.SojournMerchVo;
import com.yueyang.sojourn.server.service.member.MemberService;
import com.yueyang.sojourn.server.service.share.ShareDataService;
import com.yueyang.sojourn.server.service.sojourn.merch.ReadMerchService;
import com.yueyang.sojourn.server.service.sojourn.merch.inventory.MerchInventoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author yemingxing
 * @summary
 * @Copyright (c) 2020, Yueyang Group All Rights Reserved.
 * @since 2020-02-20 12:10
 */
@RestController
@RequestMapping("/api/wx/merch")
@Api(tags = "(小程序)商品 API")
public class ApiMerchController extends BaseController {

    @Autowired
    private ReadMerchService readMerchService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MerchInventoryService merchInventoryService;
    @Autowired
    private ShareDataService shareDataService;


    @LoginNeedless
    @ApiOperation(value = "根据商品id查询商品详情")
    @GetMapping("/{merchId}")
    public SojournMerchVo findById(@ApiParam(value = "商品id") @PathVariable Long merchId,
                                   @RequestHeader(value = "shareId", required = false) Long shareId) {
        SojournMerchVo merchVo = readMerchService.findWxVoById(merchId, getLoginUserId());
        //分销数据
        if (shareId != null && getLoginUserId() != null) {
            shareDataService.action(shareId, ShareDataTypeEnum.浏览, getLoginUserId(), "通过小程序详情页访问了商品", null);
        }
//        JAssert.pass(merchVo.getShelfStatus() == ShelfStatusEnum.BEING_ON.getCode(), "商品已下架");
        return merchVo;
    }

    @LoginNeedless
    @ApiOperation(value = "查询项目精选商品", notes = "可根据项目id和上架中状态，查询项目精选商品")
    @GetMapping("/page")
    public PageInfo<SojournMerchVo> findPage(@ApiParam(value = "所属项目id") @RequestParam(required = false) Long projectId,
//                                             @ApiParam(value = "上架状态(枚举值)") @RequestParam(required = false) Integer shelfStatus,
                                             @RequestParam int pageNo,
                                             @RequestParam int pageSize) {
        return readMerchService.findWxPage(projectId, ShelfStatusEnum.BEING_ON.getCode(), pageNo, pageSize);
    }

    @LoginNeedless
    @ApiOperation(value = "根据商品id查询商品价格日历")
    @GetMapping("/{merchId}/price/calendar")
    public SojournMerchPriceCalendarVo findPriceCalendar(@ApiParam(value = "商品id") @PathVariable Long merchId) {
        SojournMerchPriceCalendarVo calendarVo = new SojournMerchPriceCalendarVo();
        SojournMerchVo merchVo = readMerchService.findWxVoById(merchId, getLoginUserId());
        SojournMerchPriceCalendarVo.SojournMerchSimpleVo merchSimpleVo = new SojournMerchPriceCalendarVo.SojournMerchSimpleVo();
        BeanUtils.copyProperties(merchVo, merchSimpleVo);
        calendarVo.setMerch(merchSimpleVo);

        Date begin = merchVo.getAvailableDateBegin();
        Date end = merchVo.getAvailableDateEnd();
        Date tmp = begin;
        Calendar beginCal = Calendar.getInstance();
        beginCal.setTime(begin);

        // 商品每日的库存信息
        Map<Long, Integer> dayInventory = merchInventoryService.calcMerchInventory(merchVo.getId());

        LinkedHashMap<String, SojournMerchPriceMonthVo> monthPrice = new LinkedHashMap();
        SojournMerchPriceMonthVo.DefaultStartDate defaultStartDate = null;
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, 1);
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
        while (tmp.getTime() < end.getTime()) {
            tmp = beginCal.getTime();
            beginCal.get(Calendar.YEAR);
            //获取年
            int year = beginCal.get(Calendar.YEAR);
            //获取年 后两位
            int yearSimple = Integer.parseInt((year + "").substring(2));
            //获取月份，0表示1月份
            int month = beginCal.get(Calendar.MONTH) + 1;
            //获取当前天数
            int day = beginCal.get(Calendar.DAY_OF_MONTH);
            //获取当前天数
            int week = beginCal.get(Calendar.DAY_OF_WEEK) - 1;

            String monthFull = year + "-" + month;
            SojournMerchPriceMonthVo monthVo = monthPrice.get(monthFull);
            if (monthVo == null) {
                monthVo = new SojournMerchPriceMonthVo();
                monthPrice.put(monthFull, monthVo);
                monthVo.setYear(year);
                monthVo.setYearSimple(yearSimple);
                monthVo.setMonth(month);
            }

            SojournMerchPriceMonthVo.PriceDate priceDate = new SojournMerchPriceMonthVo.PriceDate();
            monthVo.getDates().add(priceDate);
            priceDate.setDay(day);
            priceDate.setWeek(week);
            priceDate.setPrice(new BigDecimal(merchVo.getPrice()));
            priceDate.setVipPrice(readMerchService.getFinalPirce(new BigDecimal(merchVo.getPrice()), MerchSaleTypeEnum.VIP));

            priceDate.setInventory(dayInventory.getOrDefault(tmp.getTime(), merchVo.getInventory()));

            //如果库存大于0，当前时间早于日历日期，则日历可选日期第一天为默认选中
            if (defaultStartDate == null && priceDate.getInventory() > 0 && (now.getTime().before(tmp) || now.getTime().equals(tmp))) {
                defaultStartDate = new SojournMerchPriceMonthVo.DefaultStartDate();
                BeanUtils.copyProperties(monthVo, defaultStartDate);
                BeanUtils.copyProperties(priceDate, defaultStartDate);
                calendarVo.setDefaultStartDate(defaultStartDate);
            }
            // 天数加上1
            beginCal.add(Calendar.DAY_OF_MONTH, 1);
        }
        monthPrice.values().stream().forEach((monthVo) -> {
            calendarVo.getPriceMonths().add(monthVo);
        });


        return calendarVo;
    }


    @ApiImplicitParam(name = "X-Token", paramType = "header", required = false)
    @LoginNeedless
    @ApiOperation(value = "根据商品id计算商品价格")
    @GetMapping("/{merchId}/price/calculate")
    //@Validated  // 启用校验
    public SojournMerchPriceCalculateVo findPriceCalculate(@ApiParam(value = "商品id") @PathVariable Long merchId,
                                                           @ApiParam(value = "商品数量") //@NotNull(message = "[商品数量]不能为空")
                                                           @RequestParam("count") Integer count,
                                                           @ApiParam(value = "商品优惠类型:以逗号分隔;如果指定则按指定优惠计算；如果不指定则按商品优惠策略")
                                                           @RequestParam(value = "sales", required = false) String sales) {
        Long loginUserId = null;
        try {
            loginUserId = getLoginUserId();
        } catch (Exception e) {

        }

        List<MerchSaleTypeEnum> saleTypeEnums = new ArrayList<>();
        if (sales != null && !sales.trim().isEmpty()) {
            String[] saleArr = sales.split(",");
            for (String saleTemp : saleArr) {
                Integer sale = Integer.parseInt(saleTemp);
                for (MerchSaleTypeEnum saleTypeEnum : MerchSaleTypeEnum.values()) {
                    if (saleTypeEnum.getCode() == sale) {
                        saleTypeEnums.add(saleTypeEnum);
                    }
                }
            }
        }

        return readMerchService.calculateMerchPrice(merchId, count, saleTypeEnums, loginUserId == null ? false : memberService.isMember(loginUserId));
    }
}
